﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SolutionModel;
using SFast.DB;
using SFast.Web;
using SFast.Encryption;
using System.Data;
using System.Data.Common;
using System.Transactions;
//using EntityFramework.Extensions;
using NLite.Data;

namespace SolutionDAL
{
    public class T_AdminUserDAL
    {

        #region 通过用户ID获取用户信息
        /// <summary>
        /// 通过用户ID获取用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<T_AdminUser> GetAdminUserByID(String id)
        {
            PurviewDBEntities db = DBConfig.GetDBContext();
            return db.T_AdminUsers.Where(o => o.UserID == id).ToList<T_AdminUser>();

        }
        #endregion

        #region 通过用户ID获取用户信息 转换为js 回填到表单中
        /// <summary>
        /// 通过用户ID获取用户信息 转换为js 回填到表单中
        /// 标记：需修改
        /// </summary>
        /// <param name="id">要查找的用户ID</param>
        /// <returns></returns>
        public void GetAdminUserByIDToJs(String id)
        {
            PurviewDBEntities db = DBConfig.GetDBContext();
            var u = db.T_AdminUsers
                .Where(o => o.UserID == id)
                .Select(o => new
                {
                    UserID = o.UserID,
                    o.Account,
                    Password = "密密密密密密",
                    o.Email,
                    o.UserName,
                    o.IsDisabled
                });
            u.FirstOrDefault()._DataToForm("form1");
        }
        #endregion

        #region 添加管理员
        /// <summary>
        /// 添加管理员
        /// </summary>
        /// <param name="obj">管理员实体</param>
        /// <pparam name="roleids">当前管理员所属的角色ID,字符串格式，用逗号分割</pparam>
        public void InsertAdminUser(T_AdminUser obj, String roleids)
        {
            PurviewDBEntities db = DBConfig.GetDBContext();
            {
                db.UsingTransaction(() =>
                {
                    try
                    {
                        //添加管理员
                        obj.Password = obj.Password._ToMD5();
                        db.T_AdminUsers.Insert(obj);

                        //给当前管理员添加角色
                        if (!String.IsNullOrEmpty(roleids))
                        {
                            var list_ids = roleids.Split(',').ToList<String>();
                            T_UsersInRolesDAL uirb = new T_UsersInRolesDAL();
                            uirb.AddOrUpdate(obj.UserID, list_ids);
                        }
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }

                });
            }
        }
        #endregion

        #region 更新管理员信息
        /// <summary>
        /// 更新管理员信息
        /// 标记：需修改
        /// </summary>
        /// <param name="userobj">要修改的对象</param>
        /// <param name="roleID">字符串以逗号分割的角色ID</param>
        /// <returns></returns>
        public bool UpdateAdminUser(T_AdminUser userobj, String roleID)
        {
            PurviewDBEntities db = DBConfig.GetDBContext();

            int r = 0;
            db.UsingTransaction(() =>
            {
                String passwordMD5 = userobj.Password._ToMD5();

                try
                {
                    //修改管理员信息
                    //如果新密码为“密密密密密密”则为不修改，把密还原为原来的密码
                    if (userobj.Password == "密密密密密密")
                    {
                        r = db.T_AdminUsers.Update(
                                new
                                {
                                    UserName = userobj.UserName,
                                    IsDisabled = userobj.IsDisabled == null ? true : userobj.IsDisabled
                                },
                                o => o.UserID == userobj.UserID  //更新条件
                            );
                    }
                    else
                    {
                        r = db.T_AdminUsers.Update(
                                new
                                {
                                    UserName = userobj.UserName,
                                    Password = passwordMD5,
                                    IsDisabled = userobj.IsDisabled == null ? true : userobj.IsDisabled
                                },
                                o => o.UserID == userobj.UserID  //更新条件
                            );
                    }

                    //删除该用户的所有角色信息
                    //db.TUsersInRoles.Delete(o => o.UserId == userobj.UserId);

                    //添加该用户的新角色信息
                    List<String> list = new List<string>();
                    if (!String.IsNullOrEmpty(roleID))
                    {
                        list = roleID.Split(',').ToList<String>();
                    }
                    //foreach (var item in list)
                    //{
                    //    db.TUsersInRoles.Insert(new TUsersInRole { RoleId = item, UserId = userobj.UserId });
                    //}
                    T_UsersInRolesDAL uirb = new T_UsersInRolesDAL();
                    uirb.AddOrUpdate(userobj.UserID, list);
                }
                catch (Exception e)
                {
                    r = 0;
                    throw e;
                }
            });
            return r > 0;

        }
        #endregion

        #region 获取用户列表
        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="size"></param>
        /// <returns></returns>
        public IQueryable<T_AdminUser> GetAdminUserList(String key)
        {
            //String sql = "SELECT * FROM dbo.T_AdminUser";
            //Pagination list = db.Exec_Pager<T_AdminUser>(sql, size, "  ORDER BY  CreateTime DESC ");
            //Pagination list = db.Exec_Pager(sql, size, "  ORDER BY  CreateTime DESC ");
            PurviewDBEntities etdb = new PurviewDBEntities();

            var q = etdb.T_AdminUsers as IQueryable<T_AdminUser>;
            if (!String.IsNullOrEmpty(key))
            {
                q = q.Where(o => o.UserName.Contains(key) || o.Account.Contains(key));
            }

            var pa = q.OrderByDescending(o => o.CreateTime).Select(o =>
                new T_AdminUser
                {
                    UserID = o.UserID,
                    UserName = o.UserName,
                    T_UsersInRoles = o.T_UsersInRoles,
                    IsDisabled = o.IsDisabled,
                    Email = o.Email,
                    CreateTime = o.CreateTime,
                    Account = o.Account
                });

            return pa;
        }
        #endregion

        #region 添加用户时验证当前用户是否已经在数据库存在
        /// <summary>
        /// 添加用户时验证当前用户是否已经在数据库存在
        /// </summary>
        /// <param name="account">用户名</param>
        /// <returns></returns>
        public int HasAdminUser(String account)
        {
            PurviewDBEntities etdb = DBConfig.GetDBContext();
            return etdb.T_AdminUsers.Where(o => o.Account == account).Count();

        }
        #endregion

        #region 通过用户名密码或取用户信息
        /// <summary>
        /// 通过用户名密码或取用户信息
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public T_AdminUser getUser(String account, String password)
        {
            PurviewDBEntities dbe = DBConfig.GetDBContext();
            password = password._ToMD5();
            return dbe.T_AdminUsers.FirstOrDefault(o => o.Account == account & o.Password == password & o.IsDisabled == true);

        }
        #endregion

    }
}
